package org.restoran.service.parser.jackson;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.restoran.model.Identifiable;
import org.restoran.model.Order;

import java.io.IOException;


/**
 *
 */
public abstract class BasePersistableBeanDeserializer<E extends Identifiable> extends JsonDeserializer<E> {

    @Override
    public E deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        E object = null;
        try {
            object = createInstance();
            int id = jp.getValueAsInt();
            object.setId(id);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new ParsingDeserializException("instance of " + Order.class + "can't be created", e);
        }
        return object;
    }

    protected abstract E createInstance() throws InstantiationException, IllegalAccessException;
}
